import React, { useEffect } from "react"
import GpContainer from "@/components/GpContainer"
import Taro from "@tarojs/taro"
import { View, PickerView, PickerViewColumn } from "@tarojs/components"
import { useSetState } from "@/utils/hooks"
import { yearOptions } from "@/constants/words"
import styles from "./index.module.scss"
import { ChooseInfoSubmit, getAreaOptions, getProjectOptions } from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import { useAppDispatch, useAppSelector } from "@/store/hook"
import { patchExtra, refreshUserInfo } from "@/store/actions/auth"
import GpNavbar from "@/components/GpNavbar"
import clsx from "clsx"

type IState = {
  currentStep: 1 | 2 | 3
  year: number[]
  provinceOptions: IApiRelative.IGetAreaOptions.IArea[]
  cityOptions: IApiRelative.IGetAreaOptions.IArea[]
  areaValue: number[]
  projectOptions: IOptionLike<number>[]
  projectValue: number[]
  disabled: boolean
}
/**
 * @page 选择高考年份等信息
 * @description 该页面在未配置的用户点击“专业百科”和“社区”出现，若用户点击跳过，下次再点击该板块不会出现
 */
export default function ChooseInfo() {
  const dispatch = useAppDispatch()
  const userInfo = useAppSelector(state => state.auth.userInfo)
  const [state, setState] = useSetState<IState>(() => {
    const year = [0]
    if (userInfo.year) {
      const index = yearOptions.findIndex(l => l.value === userInfo.year)
      if (~index) {
        year.splice(0, 1, index)
      }
    }
    return {
      currentStep: 1,
      year,
      provinceOptions: [],
      cityOptions: [],
      areaValue: [0, 0],
      projectOptions: [],
      projectValue: [0],
      disabled: false
    }
  })
  useEffect(() => {
    fetchProjectOptions()
    fetchAreaData()
  }, [])
  function handleBeforeBack() {
    dispatch(
      patchExtra({
        chooseInfoIgnored: true
      })
    )
  }
  function fetchAreaData() {
    getAreaOptions().then(res => {
      if (requestIsFullfilled(res)) {
        const areaData = res.data.data
        const areaValue = state.areaValue
        let cityOptions = state.cityOptions
        if (userInfo.areaId && /** 全国为000000 */ userInfo.areaId !== "000000") {
          const provinceId = userInfo.areaId.slice(0, 2) + "0000"
          const provinceIndex = areaData.findIndex(l => l.value === provinceId)
          if (~provinceIndex) {
            areaValue.splice(0, 1, provinceIndex)
            cityOptions = areaData[areaValue[0]].children
            const cityIndex = cityOptions.findIndex(l => l.value === userInfo.areaId)
            if (~cityIndex) {
              areaValue.splice(1, 1, cityIndex)
            }
          }
        } else {
          cityOptions = areaData[areaValue[0]].children
        }
        setState({
          provinceOptions: areaData,
          cityOptions,
          areaValue
        })
      }
    })
  }
  function fetchProjectOptions() {
    getProjectOptions().then(res => {
      if (requestIsFullfilled(res)) {
        // 过滤综合选项, 综合为3
        res.data.data = res.data.data.filter(l => l.value !== 3)
        const projectValue = state.projectValue
        if (userInfo.projectId && /** 综合为3 */ userInfo.projectId !== 3) {
          const index = res.data.data.findIndex(l => l.value === userInfo.projectId)
          if (~index) {
            projectValue.splice(0, 1, index)
          }
        }
        setState({
          projectOptions: res.data.data,
          projectValue
        })
      }
    })
  }
  function handleAction() {
    if (state.disabled) return
    if (state.currentStep !== 3) {
      setState({
        currentStep: (state.currentStep + 1) as any
      })
    } else {
      Taro.showLoading({ title: "保存中" })
      ChooseInfoSubmit({
        year: yearOptions[state.year[0]].value,
        areaId: state.cityOptions[state.areaValue[1]].value,
        projectId: state.projectOptions[state.projectValue[0]].value
      })
        .then(async res => {
          if (requestIsFullfilled(res)) {
            await dispatch(refreshUserInfo() as any)
            Taro.hideLoading()
            Taro.showToast({ title: "保存成功" })
            Taro.navigateBack()
          }
        })
        .catch(() => {
          Taro.hideLoading()
        })
    }
  }
  function handleIgnore() {
    dispatch(
      patchExtra({
        chooseInfoIgnored: true
      })
    )
    Taro.navigateBack()
  }
  function handlePickerChange(value: number[], stateKey: "year" | "projectValue") {
    setState({
      [stateKey]: value
    })
  }
  function handleAreaChange(areaValue: number[]) {
    const [nP] = areaValue
    const [oP] = state.areaValue
    // 第一列发生改变
    if (nP !== oP) {
      setState({
        areaValue: [nP, 0],
        cityOptions: state.provinceOptions[nP].children
      })
    } else {
      setState({
        areaValue
      })
    }
  }
  function handlePickerStart() {
    setState({ disabled: true })
  }
  function handlePickerEnd() {
    setState({ disabled: false })
  }
  function renderSteps() {
    if (state.currentStep === 1) {
      return renderStep1()
    } else if (state.currentStep === 2) {
      return renderStep2()
    } else if (state.currentStep === 3) {
      return renderStep3()
    }
  }
  function renderStep1() {
    return (
      <View className={styles.stepBlock}>
        <View className={styles.tipInfo}>
          <View className={styles.label}>选择高考年份(1/3)</View>
          <View className={styles.desc}>用于为你提供个性化服务</View>
        </View>
        <View className={styles.stepPicker}>
          <PickerView
            indicatorStyle="height: 50px;"
            style="width: 100%; height: 300px; background-color: #ffffff;"
            indicatorClass={styles.indicatorClass}
            value={state.year}
            onChange={ev => handlePickerChange(ev.detail.value, "year")}
            onPickStart={handlePickerStart}
            onPickEnd={handlePickerEnd}
          >
            <PickerViewColumn>
              {yearOptions.map(l => {
                return (
                  <View
                    key={l.value}
                    style={{
                      lineHeight: "50px",
                      textAlign: "center"
                    }}
                  >
                    {l.label}
                  </View>
                )
              })}
            </PickerViewColumn>
          </PickerView>
        </View>
      </View>
    )
  }
  function renderStep2() {
    return (
      <View className={styles.stepBlock}>
        <View className={styles.tipInfo}>
          <View className={styles.label}>选择省份地区(2/3)</View>
          <View className={styles.desc}>用于为你提供个性化服务</View>
        </View>
        <View className={styles.stepPicker}>
          <PickerView
            indicatorStyle="height: 50px;"
            style="width: 100%; height: 300px; background-color: #ffffff;"
            indicatorClass={styles.indicatorClass}
            value={state.areaValue}
            onChange={ev => handleAreaChange(ev.detail.value)}
            onPickStart={handlePickerStart}
            onPickEnd={handlePickerEnd}
          >
            <PickerViewColumn>
              {state.provinceOptions.map(l => {
                return (
                  <View
                    key={l.value}
                    style={{
                      lineHeight: "50px",
                      textAlign: "center"
                    }}
                  >
                    {l.title}
                  </View>
                )
              })}
            </PickerViewColumn>
            <PickerViewColumn>
              {state.cityOptions.map(l => {
                return (
                  <View
                    key={l.value}
                    style={{
                      lineHeight: "50px",
                      textAlign: "center"
                    }}
                  >
                    {l.title}
                  </View>
                )
              })}
            </PickerViewColumn>
          </PickerView>
        </View>
      </View>
    )
  }
  function renderStep3() {
    return (
      <View className={styles.stepBlock}>
        <View className={styles.tipInfo}>
          <View className={styles.label}>选择艺考方向(3/3)</View>
          <View className={styles.desc}>用于为你提供个性化服务</View>
        </View>
        <View className={styles.stepPicker}>
          <PickerView
            indicatorStyle="height: 50px;"
            style="width: 100%; height: 300px; background-color: #ffffff;"
            indicatorClass={styles.indicatorClass}
            value={state.projectValue}
            onChange={ev => handlePickerChange(ev.detail.value, "projectValue")}
            onPickStart={handlePickerStart}
            onPickEnd={handlePickerEnd}
          >
            <PickerViewColumn>
              {state.projectOptions.map(l => {
                return (
                  <View
                    key={l.value}
                    style={{
                      lineHeight: "50px",
                      textAlign: "center"
                    }}
                  >
                    {l.label}
                  </View>
                )
              })}
            </PickerViewColumn>
          </PickerView>
        </View>
      </View>
    )
  }
  function renderNavigation() {
    return <GpNavbar navigationBarTitleText="登录" onBeforeBack={handleBeforeBack} />
  }
  return (
    <GpContainer
      style={{
        backgroundColor: "#fff"
      }}
    >
      {renderNavigation()}
      <View className={styles.ignore} onClick={handleIgnore}>
        跳过
      </View>
      {renderSteps()}
      <View
        className={clsx(styles.actionBtn, {
          [styles.disabled]: state.disabled
        })}
        onClick={handleAction}
      >
        {state.currentStep === 3 ? "提交" : "下一步"}
      </View>
    </GpContainer>
  )
}
